// Copyright 2017, 2019 ETH Zürich, Thomas Schöps
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.


#include <fstream>
#include <iostream>
#include <sstream>

#include <boost/filesystem.hpp>

using namespace boost;
using namespace std;

// Helper program to convert an arbitrary binary file into a C++ file containing
// the data.
int main(int argc, char** argv) {
  // Parse parameters.
  if (argc < 2 ||
      argv[1] == string("-h") ||
      argv[1] == string("--help")) {
    cout << "Usage:" << endl << endl
         << "  bin2c [options ...] <input_file>" << endl << endl
         << "Available options:" << endl
         << "  -H <file>  Include the text in <file> as header." << endl
         << "  -n <name>  Wrap the variables in a namespace with given <name>."
         << endl << endl;
    return EXIT_FAILURE;
  }
  
  string header_path;
  string namespace_name;
  for (int i = 1; i < argc - 1; ++ i) {
    if (argv[i] == string("-H")) {
      if (i == argc - 2) {
        cout << "-H must be followed by a file path." << endl;
        return EXIT_FAILURE;
      }
      header_path = argv[i + 1];
      ++ i;
    } else if (argv[i] == string("-n")) {
      if (i == argc - 2) {
        cout << "-n must be followed by a namespace name." << endl;
        return EXIT_FAILURE;
      }
      namespace_name = argv[i + 1];
      ++ i;
    } else {
      cout << "Unknown option: " << argv[i];
      return EXIT_FAILURE;
    }
  }
  const char* input_path = argv[argc - 1];
  
  // Open the file.
  ifstream file(input_path, ios::in);
  if (!file) {
    cout << "Cannot open the input file: " << input_path << endl;
    return EXIT_FAILURE;
  }
  
  // Get the file size.
  file.seekg(0, ios_base::end);
  size_t file_size = file.tellg();
  file.seekg(0, ios_base::beg);
  
  // Read the file.
  uint8_t* buffer = new uint8_t[file_size];
  file.read(reinterpret_cast<char*>(buffer), file_size);
  file.close();
  
  // Determine the variable name for the data.
  // NOTE: Non-exhaustive character escaping.
  string variable_name = filesystem::path(input_path).filename().string();
  for (size_t i = 0; i < variable_name.size(); ++ i) {
    if (variable_name[i] == '.') {
      variable_name[i] = '_';
    } else if (variable_name[i] == '-') {
      variable_name[i] = '_';
    }
  }
  
  // Read header file if specified.
  string header;
  if (!header_path.empty()) {
    std::ifstream header_stream(header_path, std::ios::in);
    if (!header_stream) {
      cout << "Cannot read header file: " << header_path << endl;
      return EXIT_FAILURE;
    }
    char buffer[4096];
    while (header_stream.read(buffer, sizeof(buffer))) {
      header.append(buffer, sizeof(buffer));
    }
    header.append(buffer, header_stream.gcount());
    header_stream.close();
  }
  
  // Write the C++ file.
  std::ofstream output(input_path + string(".h"), std::ios::out);
  output << "// This file was autogenerated by bin2c. Do not modify."
         << endl << endl;
  if (!header.empty()) {
    output << header << endl << endl;
  }
  if (!namespace_name.empty()) {
    output << "namespace " << namespace_name << " {" << endl << endl;
  }
  output << "static constexpr uint64_t " << variable_name << "_size = "
         << file_size << ";" << endl;
  output << "static constexpr const uint8_t " << variable_name << "[] = {";
  if (file_size > 0) {
    constexpr int kLineLengthLimit = 80;
    output << endl;
    ostringstream line;
    line << "    ";
    for (size_t i = 0; i < file_size - 1; ++ i) {
      // NOTE: Inexact implementation for keeping kLineLengthLimit. The limit
      //       will not be exceeded, but the lines might not be fully used.
      if (line.tellp() >= kLineLengthLimit - 9) {
        line << static_cast<int>(buffer[i]) << "," << endl;
        output << line.str();
        line.str("");  // Reset the stream's string (but not its error flags).
        line << "    ";
      } else {
        line << static_cast<int>(buffer[i]) << ", ";
      }
    }
    line << static_cast<int>(buffer[file_size - 1]);
    output << line.str();
  }
  output << "};" << endl;
  if (!namespace_name.empty()) {
    output << endl << "}  // namespace " << namespace_name << endl;
  }
  output.close();
  
  delete[] buffer;
  return EXIT_SUCCESS;
}
